﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using D.Wx.Dtos;

namespace D.Wx.Filter
{
    /*使用方式：
     *1. 在controller里打上 [CustomExceptionFilter] 标签。
     *2. 在Startup里以filter方式全局注入。
     *services.AddControllersWithViews(options =>
     *{
     * options.Filters.Add<CustomExceptionFilterAttribute>();
     *})
     */

    /// <summary>
    /// 使用 IExceptionFilter
    /// Asp.net Core中ExceptionFilterAttribute已经实现了IExceptionFilter，所以我们只需继承ExceptionFilterAttribute
    /// </summary>
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        readonly IWebHostEnvironment hostEnvironment;

        //readonly ILog logger;
        public ExceptionFilter(IWebHostEnvironment _hostEnvironment)
        {
            this.hostEnvironment = _hostEnvironment;
        }

        /// <summary>
        /// 重写异常拦截日志
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                if (context.Exception.Message.Contains("Token错误") || context.Exception.Message.Contains("Token过期"))
                {
                    ContextReturn(context, new ApiResult<string>()
                    {
                        StatusCode = StatusCodeEnum.Unauthorized,
                        Success = false,
                        Msg = "会话已超时,请重新登录"
                    });
                    return;
                }

                if (context.Exception.InnerException.Message.Contains("无效的用户信息,请重新登录") || context.Exception.InnerException.Message.Contains("尚未认证,请登录") || context.HttpContext.Request.Path.Value.Contains("getUserInfo"))
                {
                    ContextReturn(context, new ApiResult<string>()
                    {
                        StatusCode = StatusCodeEnum.Unauthorized,
                        Success = false,
                        Msg = "尚未认证,请登录"
                    });
                    return;
                }

                ContextReturn(context, new ApiResult<string>()
                {
                    StatusCode = StatusCodeEnum.ServerError,
                    Success = false,
                    Msg = "服务器异常"
                });
                context.ExceptionHandled = true;//异常已处理
            }
        }


        /// <summary>
        /// 返回API的信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        private void ContextReturn(ExceptionContext context, ApiResult<string> apiResult)
        {
            var josnStr = JsonConvert.SerializeObject(apiResult, new JsonSerializerSettings()
            {// 返回小写
                //NullValueHandling = NullValueHandling.Ignore,
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            });

            context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
            context.Result = new ContentResult() { Content = josnStr };
            context.ExceptionHandled = true;//异常已处理
        }
    }
}
